#!/usr/bin/env python
# AMPTest - Albert's Media Performance Test
# Written by Albert Huang.
# (C) Copyright 2009 Albert Huang.
# Licensed under the GPL (v3).
#
# Note: This is an ALPHA program. 
# This may be very unstable.
# Use at your own risk!
# 
# This is the core part of AMPTest, which performs all the tests
# and displays the results.
#

# Import necessities
import os,time
import sys
import subprocess as sub
import string
import threading
import time
import datetime

# Import math functions
import math

import re

# Variables
global p
global next_line
global output

global live 
live = 0

# Debug printing function
def printer(text):
	#print datetime.datetime.now().strftime("AMPTest ("+"%A (%a) %m/%d/%Y"+" @ %I:%M:%S %p): ")+str(text)
	print datetime.datetime.now().strftime("AMPTest ("+"%a %m/%d/%Y"+" @ %I:%M:%S %p): ")+"[AMPTest_Core] "+str(text)

def grep(string,list):
	expr = re.compile(string)
	return filter(expr.search,list)

class AMPTestCore:
	def VideoHD720p(self):
		global output
		p = sub.Popen(['mplayer', '-input', 'conf="/home/arthur/input-amptest-2.conf"', '-fs', '-zoom', '-framedrop', 'andromeda_orb-stargazer.mp4'],stdout=sub.PIPE, stderr=sub.PIPE)

		#output, errors = p.communicate()

		next_line = ""
		output = ""
		printer("Running benchmark...")
		while True:
			#next_line = proc.communicate()[0]
			next_line = p.stdout.readline()

			#lines = p.stdout.readlines()[-1]
			#print lines[-1]
			#next_line = p.stdout.read(1)
			#print next_line
			if next_line == '' and p.poll() != None:
				break
			#sys.stdout.write(next_line)
			#sys.stdout.flush()
			
			if output == '':
			   output = next_line
			else:
			   if next_line != '':
				  output = output + next_line

		OUTRESULT = self.parseResults_VideoHD720p()
		return OUTRESULT
	def parseResults_VideoHD720p(self):
		global output
		# Result template:
		# A: 7.3 V: 7.3 A-V: -0.000 ct: 0.023 219/219 19% 5% 0.8% 0 0
		# 1  2   3  4   5    6      7   8     9       10  11 12   1314
		# BASH: finalframedrop=`echo $finalresult | cut -f13 -d' '`
		#print line.split(',')
		#print "DEBUG: Output is " + str(output)
		stringlist = output.split('\n')
		#print "DEBUG: Grepped string: " + grep('A:', stringlist)
		thestr = grep('A:', stringlist)

		try :
			result = thestr[-1]
		except:
			printer("FAILED TO PARSE OUTPUT. The program likely died.")
			return "0 FAILED The program failed to run."
		
		#print "STRING: "+thestr
		#print "========================================"
		#print "RESULT: "
		#print result
		#print "========================================"
		
		better_result = result.split('J\r')
		supergoodresult = grep('A:', better_result)
		final_result = supergoodresult[-1]
		
		new_s = "".join(i for i in final_result if i in "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ:%./- ")

		new_s_clean = new_s.replace('  ', ' ').replace('  ', ' ').replace('  ', ' ').replace('  ', ' ').replace('  ', ' ')
		new_s_seperate = new_s_clean.split('JA:')
		print "CLEANED: "+new_s_clean
		new_s = new_s_clean

		emptybuf = " "
		finalframedrop = 0

		try:
			# A: 7.3 V: 7.3 A-V: -0.000 ct: 0.023 219/219 19% 5% 0.8% 0 0
			split_by_slash = emptybuf.join(new_s.split('/')[1])
			#finalframedrop = emptybuf.join(new_s.split(' ')[12])
			if (emptybuf.join(split_by_slash.split(' ')[0]) == ''):
				finalframedrop = emptybuf.join(split_by_slash.split(' ')[5])
			else:
				finalframedrop = emptybuf.join(split_by_slash.split(' ')[4])
			# BASH: totalframes=`echo $finalresult | cut -f9 -d' ' | cut -f1 -d'/'`
			totalframes = emptybuf.join(emptybuf.join(new_s.split(' ')[8]).split('/')[0])
		except:
			printer("ERROR: Splitting failed. :( ")

		#print "Results:"
		#print "Original line: "+s
		#print "Stripped and filtered line: "+new_s
		#print "Really stripped line: "+new_s.replace('  ', ' ')
		#print "==================================================="
		try:
			if type(finalframedrop) == type(1):
				printer("Still not running yet! "+'(Line: '+next_line+')')
				print "Frames dropped: "+finalframedrop
			else:
				print "Total frames: "+totalframes
				# Calculate the score! :)
				percent = finalframedrop / totalframes
				score = round(percent * 20000)
				if score > 17500:
					passornot = "PASSED"
					if score == 20000:
						notes = "You definitely can play 720p HD video."
					else:
						notes = "You can play 720p HD video, but may have jitters during playback. Close any running applications and run this test again to see if your score improves."
				else:
					passornot = "FAILED"
					notes = "You can not play 720p HD video due to too many jitters that occur during playback. Try the test again after closing any open applications. If you get the same score, your computer may not be fast enough to play 720p HD video."
				return str(score)+" "+str(passornot)+" "+notes
		except:
			printer("Type detection failed! :(")
			time.sleep(5)
	def MathSQRTTest(self):
		global done
		self.start_timing()
		start = 0
		i = 0
		while i != 10000000:
			#print "The square root of " + str(i) + " is " + str(math.sqrt(i)) + "(" + str(i) + " / 1000000)"
			i = i + 1
			a = math.sqrt(i)
			b = i**2
		result = self.stop_timing()
		return result
	# Time a function.
	def start_timing(self):
		global done
		global time1
		done = 0
		time1 = time.time()
	def stop_timing(self):
		global time1
		global time2
		time2 = time.time()
		timetaken = '%s took %0.3f ms' % ("Function", (time2-time1)*1000.0)
		#print timetaken
		#print "DEBUG: Time 1 is "+str(time1)+" and time 2 is "+str(time2)
		#return res
		return timetaken
	def initTest(self):
		print "AMPTestCore v0.5 ALPHA Initialized"
		return True

global done
global res
done = 0

global output

if __name__ == "__main__":
	printer("AMPTestCore v0.5")
	printer("This usually isn't ran directly, unless you're looking for")
	printer("the console interface. This is NOT the GUI, only the console")
	printer("user interface.")
	print "Testing mathematical calculation speed..."
	res = AMPTestCore().MathSQRTTest()
	print "Result: " + str(res)
